package com.gongsir.controller;

import com.github.pagehelper.PageInfo;
import com.gongsir.entity.User;
import com.gongsir.service.UserService;
import com.gongsir.utils.MD5Util;
import com.gongsir.utils.ResponseData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author 码之泪殇
 * @date 2020/8/20 10:11
 * 到达胜利之前，无法回头
 * 用户管理类
 */
@Controller
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 查询用户信息, 支持分页和模糊搜索
     * @param page 页码
     * @param limit 限制
     * @param keywords 用户名关键字
     * @param orderBy 排序
     * @return ResponseData-Json格式
     */
    @GetMapping("/users")
    @ResponseBody
    public ResponseData getAllUser(@RequestParam(defaultValue = "1") int page,
                                   @RequestParam(defaultValue = "10") int limit,
                                   @RequestParam(value = "username", required = false,defaultValue = "") String keywords,
                                   @RequestParam(required = false,defaultValue = "id desc") String orderBy) {
        log.info("参数:page =  {},limit = {},keywords  = {},orderBy = {}",page,limit,keywords,orderBy);
        // 得到分页信息
        PageInfo<User> pageInfo = userService.getAllUser(keywords,page,limit,orderBy);
        List<User> userList = pageInfo.getList();
        ResponseData responseData = new ResponseData();
        if (!userList.isEmpty()) {
            responseData = ResponseData.ok().putDataValue("status",true)
                    .putDataValue("data",userList);
            responseData.setCount(pageInfo.getTotal());
        } else {
            responseData = ResponseData.ok().putDataValue("status",false).putDataValue("data",null);
        }
        return responseData;
    }

    /**
     * 根据id删除用户信息
     * @param id 用户id, 从url中动态解析
     * @return ResponseData
     */
    @DeleteMapping("/{id}")
    @ResponseBody
    public ResponseData deleteUserById(@PathVariable String id) {
        ResponseData responseData = new ResponseData();
        log.info("删除用户,用户ID:{}",id);
        if (null != id && !"".equals(id)) {
            int rs = userService.deleteUserById(Integer.parseInt(id));
            if (rs > 0) {
                responseData = ResponseData.ok().putDataValue("status",true).putDataValue("msg","用户删除成功");
            } else {
                responseData = ResponseData.error().putDataValue("status",false).putDataValue("msg","用户删除失败");
            }
        } else {
            responseData = ResponseData.error().putDataValue("status",false).putDataValue("msg","id为空");
        }
        return responseData;
    }

    /**
     * 添加用户信息
     * @param user 用户信息
     * @param request request
     * @return mv
     */
    @PostMapping
    public ModelAndView addUser(User user, HttpServletRequest request) {
        log.info("预添加user的信息：{}",user);
        ModelAndView mv = new ModelAndView();
        //获取用户名
        String username = user.getUsername();
        if (userService.getUserByUsername(username) != null){
            mv.setViewName("user/add_user");
            mv.addObject("msg","用户"+username+"已存在");
            return mv;
        }
        // 密码加密
        user.setPassword(MD5Util.md5(user.getPassword()));
        int rs = userService.saveUser(user);
        if (rs>0){
            mv.setViewName("redirect:page/user/user");
            mv.addObject("msg","用户:"+username+"添加成功");
        }else {
            mv.setViewName("user/add_user");
            mv.addObject("msg","用户:"+username+"添加失败");
        }
        return mv;
    }

    /**
     * 获取编辑页面, 页面带用户信息
     * @param count 用户名
     * @return mv
     */
    @GetMapping(path = "/edit")
    public ModelAndView getAdminEditPage(@RequestParam("username") String count){
        ModelAndView mv = new ModelAndView();
        User admin = userService.getUserByUsername(count);
        if (admin!=null){
            mv.clear();
            mv.setViewName("user/edit_user");
            mv.addObject("adm",admin);
        }else {
            mv.setViewName("redirect:/page/user/user");
        }
        return mv;
    }

    /**
     * 更新用户信息
     * @param user 用户信息
     * @param request request
     * @return mv
     */
    @PostMapping(path = "/edit")
    public ModelAndView editUser(User user, HttpServletRequest request){
        ModelAndView mv = new ModelAndView();
        // 判断密码是否更改
        if(!user.getPassword().equals(userService.getUserByUsername(user.getUsername()).getPassword())) {
            user.setPassword(MD5Util.md5(user.getPassword()));
        }
        int rs = userService.updateUser(user);
        if (rs>0){
            mv.setViewName("redirect:/page/user/user");
            mv.addObject("msg","数据更新成功");
        }else {
            mv.setViewName("user/edit_user");
            mv.addObject("msg","数据更新失败");
        }
        return mv;
    }

    /**
     * 修改密码
     * @param username 用户名
     * @param oldPass 原密码
     * @param password 新密码
     * @param request res
     * @return ResponseData- json
     */
    @PostMapping(path = "/upPass")
    @ResponseBody
    public ResponseData updatePassByUsername(String username, String oldPass, String password, HttpServletRequest request){
        ResponseData responseData = new ResponseData();
        // 判断原密码是否正确
        User userFormDB = userService.getUserByUsername(username);
        if (!MD5Util.md5(oldPass).equals(userFormDB.getPassword())) {
            responseData.setCode(0);
            responseData.setMsg("原密码不正确");
            return responseData;
        }
        User user = new User();
        user.setId(userFormDB.getId());
        user.setPassword(MD5Util.md5(password));
        // 更新DB
        int rs = userService.updateUser(user);
        if (rs>0){
            responseData.setMsg("密码修改成功,请重新登录");
            responseData.setCode(100);
            // 清除session
            request.getSession().removeAttribute("admin");
        }else {
            responseData.setMsg("密码修改失败,请稍后重试");
            responseData.setCode(1);
        }
        return responseData;
    }
}
